package com.fragment;

import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.Enum.InfoType;
import com.act.Answer_DetailAct;
import com.act.Question_AskAct;
import com.act.Question_DetailAct;
import com.act.SearchAct;
import com.act.UserInfoAct;
import com.bean.DynamicList;
import com.bean.SearchItem;
import com.common.Constant;
import com.control.UserControl;
import com.loopj.android.http.TextHttpResponseHandler;
import com.mUI.XListView;
import com.mUI.XListView.IXListViewListener;
import com.umeng.analytics.MobclickAgent;
import com.xike.kyt.R;
import com.xike.util.MyUtil;

public class FirstFragment extends BaseFragment implements OnClickListener {

	private static final int REQUEST_CODE_TO_ASK = 1;
	private static final int REQUEST_CODE_ASK_TO_LOGIN = 3;

	TextView tv_search, tv_ask;
	XListView listView;

	MyAdapter adapter;

	int pageCursor = 1;
	DynamicList dynamicList;
	ArrayList<SearchItem.Result> dynamics = new ArrayList<SearchItem.Result>();

	boolean isRefresh = false;
	boolean isLoadingMore = false;

	long timestamp;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_TO_ASK && resultCode > 0) {
			isRefresh = true;
			serviceGetIndex();
		}

		if (requestCode == REQUEST_CODE_ASK_TO_LOGIN && resultCode > 0) {
			Intent it_qusetion = new Intent(getActivity(), Question_AskAct.class);
			startActivityForResult(it_qusetion, REQUEST_CODE_TO_ASK);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.frag_first, null);
		initViews(view);
		return view;
	}

	private void initViews(View view) {
		tv_search = (TextView) view.findViewById(R.id.first_tv_search);
		tv_ask = (TextView) view.findViewById(R.id.first_tv_ask);
		tv_search.setOnClickListener(this);
		tv_ask.setOnClickListener(this);

		listView = (XListView) view.findViewById(R.id.first_listView);
		listView.setPullRefreshEnable(true);
		listView.setPullLoadEnable(true);
		listView.setAutoLoadEnable(true);

		listView.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				timestamp = System.currentTimeMillis();
				pageCursor = 1;
				isRefresh = true;
				serviceGetIndex();
			}

			@Override
			public void onLoadMore() {
				pageCursor++;
				isLoadingMore = true;
				serviceGetIndex();
			}
		});

		adapter = new MyAdapter();
		listView.setAdapter(adapter);
		timestamp = System.currentTimeMillis();
		serviceGetIndex();
	}

	private void updateViews() {
		ArrayList<SearchItem.Result> loadQuestions = dynamicList.getDynamics();
		if (loadQuestions == null || loadQuestions.size() <= 0) {
			if (isRefresh) {
				revertListViewRevert();
			}
		} else {
			if (isRefresh) {
				dynamics.clear(); // 刷新 清空
				dynamics.addAll(loadQuestions);
				adapter.notifyDataSetChanged();
				listView.stopRefresh();
				listView.updateRefreshTime();
				isRefresh = false;
				listView.setPullLoadEnable(true);
			} else {
				dynamics.addAll(loadQuestions);
				adapter.notifyDataSetChanged();
				if (isLoadingMore) {
					listView.stopLoadMore();
				}
				if (dynamicList.getNext_cursor() > 0) {
					listView.showFooterView();
				} else {
					listView.setPullLoadEnable(false);
				}
			}
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					SearchItem.Result dynamic = adapter.getItem(position - 1);
					int infoType = dynamic.getInfo_type();
					if (infoType == InfoType.Question.getIntValue()) {
						Intent it_questionDetail = new Intent(getActivity(), Question_DetailAct.class);
						it_questionDetail.putExtra("questionId", dynamic.getInfo_id());
						startActivity(it_questionDetail);
					} else if (infoType == InfoType.Answer.getIntValue()) {
						Intent it_questionDetail = new Intent(getActivity(), Answer_DetailAct.class);
						it_questionDetail.putExtra("answerId", dynamic.getInfo_id());
						startActivity(it_questionDetail);
					}
				}

			});
		}
	}

	private void serviceGetIndex() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("page_cursor", String.valueOf(pageCursor)));
		params.add(new BasicNameValuePair("page_count", String.valueOf(Constant.LIST_PAGESIZE)));
		params.add(new BasicNameValuePair("timestamp", String.valueOf(timestamp)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_INDEX, params);
		// // 本地缓存
		// if (LocalFileHelper.getInstance(getActivity()).fileIsExited(strUrl)) {
		// DynamicList result = gson.fromJson(LocalFileHelper.getContentFromFile(strUrl), DynamicList.class);
		// dealRequestResult(result);
		// return;
		// }

		client.get(getActivity(), strUrl, new TextHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				DynamicList result = gson.fromJson(responseString, DynamicList.class);
				dealRequestResult(result);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(getActivity(), getResources().getString(R.string.net_error));
				revertListViewRevert();

			}
		});
	}

	private void dealRequestResult(DynamicList result) {
		if (result != null) {
			if (result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
				dynamicList = result;
				updateViews();
			} else {
				revertListViewRevert();
				mToast.showToast(getActivity(), result.getError_description());
			}
		} else {
			mToast.showToast(getActivity(), getString(R.string.net_error));
			revertListViewRevert();
		}
	}

	private class MyAdapter extends BaseAdapter {

		class ViewHolder {
			ImageView img_userImg;
			TextView tv_userName, tv_type, tv_title, tv_summary, tv_createTime;
		}

		@Override
		public int getCount() {
			return dynamics.size();
		}

		@Override
		public SearchItem.Result getItem(int position) {
			return dynamics.get(position);
		}

		@Override
		public long getItemId(int position) {
			return getItem(position).getInfo_id();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = View.inflate(getActivity(), R.layout.listitem_dynamic, null);
				holder.img_userImg = (ImageView) convertView.findViewById(R.id.lvitem_img_questionUserImg);
				holder.tv_userName = (TextView) convertView.findViewById(R.id.lvitem_tv_questionUserName);
				holder.tv_type = (TextView) convertView.findViewById(R.id.lvitem_tv_questionType);
				holder.tv_title = (TextView) convertView.findViewById(R.id.lvitem_tv_questionTitle);
				holder.tv_summary = (TextView) convertView.findViewById(R.id.lvitem_tv_questionSummary);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final SearchItem.Result dynamic = getItem(position);
			MyUtil.setTextViewText(holder.tv_userName, dynamic.getUser_name(), 0, "未知用户");
			BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);
			MyUtil.displayImageView(getActivity(), dynamic.getUser_avator(), holder.img_userImg, bd.getBitmap(), false);

			// int infoTypeId = dynamic.getInfo_type();
			// int operateTypeId = dynamic.getOperate_type();
			// InfoType infoType = InfoType.getByIntValue(infoTypeId);
			// OperateType operateType = OperateType.getByIntValue(operateTypeId);
			// String strQuestionType = "";
			// if (infoType != null && operateType != null) {
			// String strInfoType = infoType.toString();
			// String strOperateType = operateType.toString();
			// strQuestionType = strOperateType + strInfoType;
			// }
			MyUtil.setTextViewText(holder.tv_type, dynamic.getDescription(), View.INVISIBLE, "");
			MyUtil.setTextViewText(holder.tv_title, dynamic.getTitle(), View.INVISIBLE, "");
			MyUtil.setTextViewText(holder.tv_summary, dynamic.getContent(), View.GONE, "");// TODO 首页暂时用问题的列表，但是服务端返回的是动态entity,所有暂用content

			holder.img_userImg.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					intentToUserInfoAct(dynamic.getUser_id());
				}
			});

			holder.tv_userName.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					intentToUserInfoAct(dynamic.getUser_id());
				}
			});
			return convertView;
		}

		private void intentToUserInfoAct(long userId) {
			Intent it_userInfo = new Intent(getActivity(), UserInfoAct.class);
			it_userInfo.putExtra("userId", userId);
			startActivity(it_userInfo);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.first_tv_search:
			startActivity(new Intent(getActivity(), SearchAct.class));
			break;
		case R.id.first_tv_ask:
			if (UserControl.isLogined()) {
				Intent it_qusetion = new Intent(getActivity(), Question_AskAct.class);
				startActivityForResult(it_qusetion, REQUEST_CODE_TO_ASK);
			} else {
				MyUtil.intentToLogin(getActivity(), REQUEST_CODE_ASK_TO_LOGIN);
			}

			break;
		default:
			break;
		}
	}

	private void revertListViewRevert() {
		if (isRefresh) {
			listView.stopRefresh();
			isRefresh = false;
		} else if (isLoadingMore) {
			listView.stopLoadMore();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("FirstFragment"); // 统计页面
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("FirstFragment");
	}

}
